<template>
  <div class="asset-overview-container">
    <h2>资产概览</h2>
    <el-card class="overview-card">
      <div class="overview-stats">
        <div class="stat-item">
          <div class="stat-label">总资产数量</div>
          <div class="stat-value">{{ overviewData.totalCount || 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">总资产价值</div>
          <div class="stat-value price">¥{{ formatMoney(overviewData.totalValue || 0) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">近30天新增</div>
          <div class="stat-value">{{ overviewData.newAssetsCount || 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">近30天报废</div>
          <div class="stat-value">{{ overviewData.scrapAssetsCount || 0 }}</div>
        </div>
      </div>
    </el-card>
    
    <div class="trend-section">
      <h3>资产价值趋势</h3>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleDateRangeChange"
        class="date-picker"
      />
      <el-card>
        <div id="valueTrendChart" class="chart"></div>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'

export default {
  name: 'AssetOverview',
  setup() {
    const overviewData = ref({})
    const dateRange = ref([
      new Date(new Date().getFullYear(), new Date().getMonth() - 6, 1),
      new Date()
    ])
    let valueTrendChart = null

    // 获取资产概览数据
    const getOverviewData = async () => {
      try {
        const response = await axios.get('/api/statistics/overview')
        if (response.code === 200) {
          overviewData.value = response.data
        } else {
          // 使用模拟数据
          overviewData.value = {
            totalCount: 1234,
            totalValue: 1560000.50,
            newAssetsCount: 45,
            scrapAssetsCount: 12
          }
        }
      } catch (error) {
        console.error('获取概览数据失败:', error)
        // 使用模拟数据
        overviewData.value = {
          totalCount: 1234,
          totalValue: 1560000.50,
          newAssetsCount: 45,
          scrapAssetsCount: 12
        }
      }
    }

    // 获取价值趋势数据
    const getValueTrendData = async () => {
      const startDate = formatDate(dateRange.value[0])
      const endDate = formatDate(dateRange.value[1])
      
      try {
        const response = await axios.get('/api/statistics/value-trend', {
          params: { startDate, endDate }
        })
        if (response.code === 200 && response.data) {
          initValueTrendChart(response.data)
        } else {
          // 使用模拟数据
          initValueTrendChart([
            { date: '2024-06', value: 1250000 },
            { date: '2024-07', value: 1320000 },
            { date: '2024-08', value: 1480000 },
            { date: '2024-09', value: 1510000 },
            { date: '2024-10', value: 1560000 },
            { date: '2024-11', value: 1630000 }
          ])
        }
      } catch (error) {
        console.error('获取价值趋势数据失败:', error)
        // 使用模拟数据
        initValueTrendChart([
          { date: '2024-06', value: 1250000 },
          { date: '2024-07', value: 1320000 },
          { date: '2024-08', value: 1480000 },
          { date: '2024-09', value: 1510000 },
          { date: '2024-10', value: 1560000 },
          { date: '2024-11', value: 1630000 }
        ])
      }
    }

    // 初始化价值趋势图表
    const initValueTrendChart = (data) => {
      if (valueTrendChart) {
        valueTrendChart.dispose()
      }
      valueTrendChart = echarts.init(document.getElementById('valueTrendChart'))
      const dates = data.map(item => item.date)
      const values = data.map(item => item.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return params[0].name + '<br/>资产价值: ¥' + formatMoney(params[0].value)
          }
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: function(value) {
              return '¥' + (value / 10000) + '万'
            }
          }
        },
        series: [
          {
            data: values,
            type: 'line',
            smooth: true,
            lineStyle: {
              color: '#1890ff',
              width: 3
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(24, 144, 255, 0.3)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(24, 144, 255, 0.1)'
                  }
                ]
              }
            }
          }
        ]
      }
      valueTrendChart.setOption(option)
    }

    // 格式化金额
    const formatMoney = (value) => {
      return Number(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }

    // 格式化日期
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    // 处理日期范围变化
    const handleDateRangeChange = () => {
      getValueTrendData()
    }

    // 监听窗口大小变化
    const handleResize = () => {
      if (valueTrendChart) {
        valueTrendChart.resize()
      }
    }

    onMounted(() => {
      getOverviewData()
      getValueTrendData()
      window.addEventListener('resize', handleResize)
    })

    onBeforeUnmount(() => {
      if (valueTrendChart) {
        valueTrendChart.dispose()
      }
      window.removeEventListener('resize', handleResize)
    })

    return {
      overviewData,
      dateRange,
      formatMoney,
      handleDateRangeChange
    }
  }
}
</script>

<style scoped>
.asset-overview-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

h3 {
  margin: 30px 0 20px 0;
  color: #303133;
}

.overview-card {
  margin-bottom: 30px;
}

.overview-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 30px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
}

.stat-value.price {
  font-size: 32px;
}

.date-picker {
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 400px;
}
</style>